from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django import http
from django.views import View
import json
import re
from django.contrib.auth import login
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from django.contrib.auth import logout
from django.http import JsonResponse

from apps.users.models import User, Address
from meiduo_mall.settings.dev import logger
from meiduo_mall.utils.secret import SecretOauth
from meiduo_mall.utils.models import BaseModel
from django.db import models

from apps.goods.models import SKU



# 注意User的导包路径
from django_redis import get_redis_connection

from apps.users.models import User

class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        '''判断用户名是否重复'''
        # 1.查询username在数据库中的个数
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return http.JsonResponse({'code':400, 'errmsg':'访问数据库失败'})

        # 2.返回结果(json) ---> code & errmsg & count
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'count':count})



class MobileCountView(View):

    def get(self, request, mobile):
        '''判断手机号是否重复注册'''
        # 1.查询mobile在mysql中的个数
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return http.JsonResponse({'code':400, 'errmsg':'查询数据库出错'})

        # 2.返回结果(json)
        return http.JsonResponse({'code':0, 'errmsg':'ok', 'count':count})


from apps.users.models import User
from rest_framework import serializers

class UserModelSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(write_only=True)
    sms_code = serializers.CharField(write_only=True)
    allow = serializers.BooleanField(write_only=True)

    class Meta:
        model = User
        fields = ['username', 'password', 'mobile', 'password2', 'sms_code', 'allow']
        extra_kwargs = {
            'username' :{
                'max_length':20,
                'min_length':5
            },
            'password':{
                'write_only':True
            }
        }
    def validate(self, attrs):
        mobile = attrs.get('mobile')
        sms_code_client = attrs.get('sms_code')
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms%s' % mobile)
        if not sms_code_server:
            raise serializers.ValidationError('验证码已失效,请重新操作')
        if sms_code_client != sms_code_server.decode():
            raise serializers.ValidationError('验证码有误,请重新输入')
        return attrs

    def create(self, validated_data):
        del validated_data['psssqord2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = User.objects.create(**validated_data)

        return user


class RegisterView(View):

    def post(self, request):
        '''接收参数, 保存到数据库'''
         # 1.接收参数：请求体中的JSON数据 request.body
        json_bytes = request.body # 从请求体中获取原始的JSON数据，bytes类型的
        json_str = json_bytes.decode() # 将bytes类型的JSON数据，转成JSON字符串
        json_dict = json.loads(json_str) # 将JSON字符串，转成python的标准字典
        # json_dict = json.loads(request.body.decode())

        # 提取参数
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        allow = json_dict.get('allow')
        sms_code = json_dict.get('sms_code')

        # 2.校验(整体参数是否为空)
        if not all([username, password, password2, mobile, sms_code]):
            return http.JsonResponse({'code':400, 'errmsg':'缺少必传参数!'})

        # 3.username检验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400, 'errmsg': 'username格式有误!'})

        # 4.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误!'})

        # 5.password2 和 password
        if password != password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入不对!'})
        # 6.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误!'})
        # 7.allow检验
        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': 'allow格式有误!'})

        # 判断短信验证码是否正确：跟图形验证码的验证一样的逻辑
        # 提取服务端存储的短信验证码：以前怎么存储，现在就怎么提取
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)  # sms_code_server是bytes
        # 判断短信验证码是否过期
        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        # 对比用户输入的和服务端存储的短信验证码是否一致
        if sms_code != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})


        # 8.注册的核心逻辑-保存到数据库 (username password mobile)
        try:
            user =  User.objects.create_user(username=username,
                                             password=password,
                                             mobile=mobile)
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '注册失败!'})

        login(request, user)

        # 13.拼接json返回
        # 生成响应对象
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})

        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        return response




import json
from django.contrib.auth import login, authenticate
from apps.carts.utils import merge_cart_cookie_to_redis
class LoginView(View):

    def post(self, request):
        '''实现登录接口'''
        # 1.接收参数
        data_dict = json.loads(request.body.decode())
        username = data_dict.get('username')
        password = data_dict.get('password')
        remembered = data_dict.get('remembered')


        # 2.校验(整体 + 单个)
        if not all([username, password]):
            return http.JsonResponse({'code': 400,'errmsg': '缺少必传参数'})

        # 多账号登录
        # 实现多账号登录
        # 判断用户输入的账号是用户名还是手机号
        if re.match(r'^1[3-9]\d{9}$', username):
            # 用户输入的账号是手机号:将USERNAME_FIELD指定为'mobile'字段
            User.USERNAME_FIELD = 'mobile'
        else:
            # 用户输入的账号是用户名:将USERNAME_FIELD指定为'username'字段
            User.USERNAME_FIELD = 'username'




        # 3.验证是否能够登录
        user = authenticate(username=username, password=password)

        # 判断是否为空,如果为空,返回
        if user is None:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名或者密码错误'})

        # 4.状态保持
        login(request, user)

        # 5.判断是否记住用户
        if remembered != True:
            # 7.如果没有记住: session立刻失效
            request.session.set_expiry(0)
        else:
            # 6.如果记住:  session设置为两周有效
            request.session.set_expiry(None)

        # 8.返回json

        # 生成响应对象
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})

        # 合并购物车
        merge_cart_cookie_to_redis(request, response)

        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        return response



# 退出登录

# 导入:
from django.contrib.auth import logout

class LogoutView(View):
    """定义退出登录的接口"""

    def delete(self, request):
        """实现退出登录逻辑"""

        # 清理 session
        logout(request)

        # 创建 response 对象.
        response = http.JsonResponse({'code':0, 'errmsg':'ok'})

        # 调用对象的 delete_cookie 方法, 清除cookie
        response.delete_cookie('username')

        # 返回响应
        return response


from rest_framework import serializers
class UserInfoSerializer(serializers.Serializer):
    username = serializers.CharField()
    mobile = serializers.CharField()
    email = serializers.CharField()
    email_active = serializers.BooleanField()

class UserInfoModelSerializer(serializers.Serializer):
    class Meta:
        model = User
        fields = ['username', 'mobile', 'email', 'email_active']


class UserInfoView(LoginRequiredMixin, View): #　用户中心
    """用户中心"""

    def get(self, request):
        """提供个人信息界面"""

        # 获取界面需要的数据,进行拼接
        info_data = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }

        # 返回响应
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'info_data': info_data})


import logging
logger = logging.getLogger('django')

# 6. 添加邮箱
class EmailView(LoginRequiredJSONMixin, View):
    def put(self, request):
        # 3.接收参数 email 校验 email正则
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 4.修改User类 request.user.email = new_email
        request.user.email = email
        request.user.save()

        # 发邮件
        from apps.users.utils import generate_verify_email_url
        verify_url = generate_verify_email_url(request)
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email, verify_url)

        # 5. request.user.save()
        # 6.返回结果
        return JsonResponse({'code': 0, 'errmsg': 'OK'})

class VerifyEmailView(View):
    def put(self, request):
        # - 1.接收 token
        token = request.GET.get('token')

        if not token:
            return JsonResponse({'code': 400, 'errmsg': 'token缺少'})

        # - 2.解密
        data_dict = SecretOauth().loads(token)

        # - 4.去数据库对比 user_id,email
        try:
            user = User.objects.get(pk=data_dict.get('user_id'), email=data_dict.get('email'))
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '参数有误!'})

        # - 5.修改激活状态
        user.email_active = True
        user.save()

        return JsonResponse({'code': 0, 'errmsg': '激活成功!'})


"""新增地址"""
class CreateAddressView(View):
    """新增地址"""

    def post(self, request):
        """实现新增地址逻辑"""

        # 获取地址个数:
        count = Address.objects.filter(user=request.user,is_deleted=False).count()

        # 判断是否超过地址上限：最多20个
        if count >= 20:
            return http.JsonResponse({'code': 400, 'errmsg': '超过地址数量上限'})

        # 1. 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 2. 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})


        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,  'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )

            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '新增地址失败'})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return http.JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address':address_dict})

"""用户收货地址"""
class AddressView(View):
    """用户收货地址"""

    def get(self, request):
        """提供地址管理界面
        """
        # 获取所有的地址:
        addresses = Address.objects.filter(user=request.user,  is_deleted=False)

        # 创建空的列表
        address_dict_list = []
        # 遍历
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': 'address_dict_list',
                                  'default_address_id': 'default_id'})

"""修改和删除地址"""
class UpdateDestroyAddressView(View):
    """修改和删除地址"""

    def put(self, request, address_id):
        """修改地址"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})


        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user = request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '更新地址成功',
                                  'address': address_dict})
    def delete(self, request, address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '删除地址成功'})

"""设置默认地址"""
class DefaultAddressView(View):
    """设置默认地址"""

    def put(self, request, address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '设置默认地址成功'})

"""设置地址标题"""
class UpdateTitleAddressView(View):
    """设置地址标题"""

    def put(self, request, address_id):
        """设置地址标题"""
        # 接收参数：地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)

            # 设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '设置地址标题失败'})

        # 4.响应删除地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '设置地址标题成功'})

"""修改密码"""
class ChangePasswordView(LoginRequiredMixin, View):
    """修改密码"""

    def put(self, request):
        """实现修改密码逻辑"""
        # 接收参数
        dict = json.loads(request.body.decode())
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
           return http.JsonResponse({'code':400,
                                     'errmsg':'缺少必传参数'})


        result = request.user.check_password(old_password)
        if not result:
            return http.JsonResponse({'code':400,
                                      'errmsg':'原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.JsonResponse({'code':400,
                                      'errmsg':'密码最少8位,最长20位'})

        if new_password != new_password2:
            return http.JsonResponse({'code':400,
                                      'errmsg':'两次输入密码不一致'})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':400,
                                      'errmsg':'修改密码失败'})

        # 清理状态保持信息
        logout(request)

        response = http.JsonResponse({'code':0,
                                      'errmsg':'ok'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response

'''8.增加收货地址'''
class CreateAddressView(LoginRequiredJSONMixin, View):
    def post(self, request):

        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 2.校验参数  -判空 --判正则

        # 3.增加
        try:
            address = Address.objects.create(
                user=request.user,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,

                title=receiver,
                receiver=receiver,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email

            )

            # 判断用户  是否 设置 默认 地址
            if not request.user.default_address:
                request.user.default_address= address
                request.user.save()

        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '增加失败!'})

        # 4.address == >address_dict
        address_dict = {
            "id": address.id,
            "title":address.title ,
            "receiver": address.receiver,

            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,

            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0, 'errmsg': '增加成功!', 'address':address_dict})



'''9. 浏览记录'''
class UserBrowseHistory(LoginRequiredJSONMixin, View):
    def post(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 2.校验参数
        try:
            SKU.objects.get(pk=sku_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': 'sku不存在'})

        # 3.redis--pipeline--lrem --lpush --ltrim --execute
        # list user.id:[1, 2 ,3]
        client = get_redis_connection('history')
        save_key = 'history_%s' % request.user.id
        p1 = client.pipeline()
        # 去重
        p1.lrem(save_key, 0, sku_id)
        # 插入
        p1.lpush(save_key, sku_id)
        # 切片
        p1.ltrim(save_key, 0,4)
        p1.ltrim(save_key, 0, 4)
        p1.execute()

        # 4.返回响应对象
        return JsonResponse({'code': 0, 'errmsg': '记录成功!'})

    def get(self, request):
        # 2.1 获取用户id  request.user.id
        save_key = "history_%s" % request.user.id
        # 2.2 链接redis     lrange(k , 0,-1)
        client = get_redis_connection('history')
        sku_ids = client.lrange(save_key, 0, -1)

        # 2.3 遍历 sku_ids --->SKU 找 sku 对象
        skus_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(pk=sku_id)
            skus_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

        # 下面 这段代码  从获取skus的角度是没有任何问题 ; 但是顺序不对
        # skus = SKU.objects.filter(pk__in=sku_ids)
        # for sku in skus:
        #     skus_list.append({
        #         'id': sku.id,
        #         'name': sku.name,
        #         'default_image_url': sku.default_image.url,
        #         'price': sku.price
        #     })

        # 2.4 json([{}])
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'skus': skus_list})


